package cn.cdu.data.utils;

import cn.cdu.basics.exception.Exception;
import cn.cdu.data.config.OssProperties;
import cn.cdu.data.vo.OssSettingVo;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 阿里云OSS工具类
 */
@Component
public class AliOssUtil implements FileManage {

    @Autowired
    private OssProperties ossProperties;

    @Override
    public String inputStreamUpload(InputStream inputStream, String key, MultipartFile file) {
        try {
            // 头像统一存储到 hospital_order/avatar 目录
            String avatarKey = key;
            if (!key.startsWith(ossProperties.getAvatarDir() + "/")) {
                avatarKey = ossProperties.getAvatarDir() + "/" + key;
            }
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret()
            );

            // 创建上传文件的元信息
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(file.getSize());

            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucketName(), avatarKey, inputStream, metadata);

            // 上传文件
            ossClient.putObject(putObjectRequest);

            // 关闭OSSClient
            ossClient.shutdown();

            // 返回文件访问路径
            return "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint() + "/" + avatarKey;
        } catch (Exception e) {
            throw new Exception("上传文件到阿里云OSS失败：" + e.getMessage());
        }
    }

    @Override
    public void deleteFile(String key) {
        try {
            OSS ossClient = new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret()
            );
            ossClient.deleteObject(ossProperties.getBucketName(), key);
            ossClient.shutdown();
        } catch (Exception e) {
            throw new Exception("从阿里云OSS删除文件失败：" + e.getMessage());
        }
    }

    @Override
    public String copyFile(String fromKey, String toKey) {
        try {
            OSS ossClient = new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret()
            );
            ossClient.copyObject(ossProperties.getBucketName(), fromKey, ossProperties.getBucketName(), toKey);
            ossClient.shutdown();
            return "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint() + "/" + toKey;
        } catch (Exception e) {
            throw new Exception("在阿里云OSS中复制文件失败：" + e.getMessage());
        }
    }

    @Override
    public String renameFile(String fromKey, String toKey) {
        try {
            OSS ossClient = new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret()
            );
            ossClient.copyObject(ossProperties.getBucketName(), fromKey, ossProperties.getBucketName(), toKey);
            ossClient.deleteObject(ossProperties.getBucketName(), fromKey);
            ossClient.shutdown();
            return "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint() + "/" + toKey;
        } catch (Exception e) {
            throw new Exception("在阿里云OSS中重命名文件失败：" + e.getMessage());
        }
    }

    @Override
    public OssSettingVo getOssSetting() {
        return new OssSettingVo(
            "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint(),
            "https://",
            ossProperties.getBucketName()
        );
    }

    /**
     * 生成带签名的临时访问URL
     * @param key OSS文件key
     * @param expireSeconds 过期时间（秒）
     * @return 签名URL
     */
    public String generatePresignedUrl(String key, int expireSeconds) {
        OSS ossClient = new OSSClientBuilder().build(
            ossProperties.getEndpoint(),
            ossProperties.getAccessKeyId(),
            ossProperties.getAccessKeySecret()
        );
        java.util.Date expiration = new java.util.Date(System.currentTimeMillis() + expireSeconds * 1000L);
        java.net.URL url = ossClient.generatePresignedUrl(ossProperties.getBucketName(), key, expiration);
        ossClient.shutdown();
        return url.toString();
    }
} 